package com.skyline.user.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.skyline.base.controller.BaseController;
import com.skyline.common.util.Constant;
import com.skyline.common.util.FreeMarkerUtils;
import com.skyline.common.util.MailUtils;
import com.skyline.common.util.ViewPaths;
import com.skyline.common.util.WebHelper;
import com.skyline.user.model.EmailToken;
import com.skyline.user.model.User;
import com.skyline.user.service.AccountInfoService;
import com.skyline.user.service.EmailTokenService;
import com.skyline.user.type.EmailTokenType;

@RequestMapping("/user")
@Controller
public class UserController extends BaseController {

	@Autowired
	private AccountInfoService accountInfoService;

	@Autowired
	private EmailTokenService emailTokenService;

//	@Value("${view.user.findPswdRequest}")
//	private String findPswdRequestView;
//
//	@Value("${view.user.findPswdByEmail}")
//	private String findPswdByEmailView;
//
//	@Value("${view.user.findPswdByAnswer}")
//	private String findPswdByAnswerView;
//
//	@Value("${view.user.modifyPassword}")
//	private String modifyPasswordView;
//
//	@Value("${view.user.modifyPasswordSuccess}")
//	private String modifyPasswordSuccessView;
//
//	@Value("${view.user.resetPassword}")
//	private String resetPasswordView;
//
//	@Value("${view.user.accountInfoMidification}")
//	private String accountInfoMidificationView;
//
//	@Value("${view.user.recommendFindPswdByEmail}")
//	private String recommendFindPswdByEmailView;

//	private static final Log LOGGER = LogFactory.getLog(UserController.class);

	/**
	 * 找回密码的请求
	 * 
	 * @return
	 */
	@RequestMapping(value = "/password/find", method = RequestMethod.GET)
	public ModelAndView findPaswordRequest() {
		ModelAndView mav = new ModelAndView();
		WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_STAT, FindPswdStat.REQUESTED);
		mav.setViewName(ViewPaths.USER_FINDPSWDREQUEST);
		return mav;
	}

	/**
	 * 找回密码方式的提交
	 * 
	 * @param email
	 *            用户的e-mail
	 * @param findType
	 *            用户通过何种方式来找回密码 <br>
	 *            0:通过安全E-mail <br>
	 *            1:通过回答安全问题 <br>
	 *            2:向我们审述（目前还没有实现）
	 * 
	 * @return
	 */
	@RequestMapping(value = "/password/find", method = RequestMethod.POST)
	public ModelAndView findPaswordExecute(String email, Integer findType) {
		ModelAndView mav = new ModelAndView();
		// System.out.println(findType);
		FindPswdStat findPswdStat = (FindPswdStat) WebHelper.getSessionAttribute(null, Constant.SESSION_FIND_PSWD_STAT);
		if (findPswdStat != null || findPswdStat != FindPswdStat.FINISHED) {
			// 运行步骤出错了；
		}
		User user = accountInfoService.getAccountInfoByEmail(email);
		if (user == null) {
			// 用户不存在
			mav.setViewName(ViewPaths.USER_FINDPSWDREQUEST);
			mav.addObject("errorMessage", "你所输入的用户不存在。");
		} else {

			WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_USER, user);
			// 用户请求通过安全email来找回密码
			if (findType == 0) {
				String toSendEmail = null;
				if (user.getSecurityEmail() != null) {
					toSendEmail = user.getSecurityEmail();
					mav.addObject("message", "成功发送到您的安全E-mail(" + toSendEmail + ")。");
				} else {
					toSendEmail = email;
					mav.addObject("message", "成功发送到您的E-mail(" + toSendEmail + ")。");
				}
				mav.addObject("email", email);
				EmailToken token = emailTokenService.addToken(user.getId(), email, EmailTokenType.PASSWORD_FIND);
				String emailTitle = FreeMarkerUtils.getForgetPasswordMailTitle(email);
				String emailContent = FreeMarkerUtils.getForgetPasswordMailContent(email, token.getToken());
				// emailTitle,emailContent输出已经测试过了
				MailUtils.sendHtmlMail(toSendEmail, emailTitle, emailContent);
				WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_STAT, FindPswdStat.FINISHED);
				mav.setViewName(ViewPaths.USER_FINDPSWDBYEMAIL);
			}
			// 通过回答问题来找回密码
			else if (findType == 1) {
				String securityQuestion = user.getSecurityQuestion();
				if (securityQuestion != null) {
					mav.addObject("securityQuestion", securityQuestion);
					WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_STAT, FindPswdStat.REQUEST_TO_ANSWER_QUESTION);
					WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_QUESTION_ANSWERED, 0);
				} else {
					// 建议用户转到通过E-mail来找回密码
					mav.setViewName(ViewPaths.USER_RECOMMENDFINDPSWDBYEMAIL);
					mav.addObject("email", email);
				}
				mav.addObject("email", email);
				mav.setViewName(ViewPaths.USER_FINDPSWDBYANSWER);
			} else {
				// TODO:目前还没有设计其它的找回密码的方式，这边留作通过申诉来找回密码。
			}
		}
		return mav;
	}

	/**
	 * 通过回答安全提问来找回密码
	 * 
	 * @param securityAnswer
	 *            用户自己所定义的安全答案
	 * @return
	 */
	@RequestMapping(value = "/password/find/answerQuestion", method = RequestMethod.POST)
	public ModelAndView answerQuestion(String securityAnswer) {
		ModelAndView mav = new ModelAndView();
		User user = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_FIND_PSWD_USER);
		FindPswdStat findPswdStat = (FindPswdStat) WebHelper.getSessionAttribute(null, Constant.SESSION_FIND_PSWD_STAT);
		Integer tryAnswerTime = (Integer) WebHelper.getSessionAttribute(null, Constant.SESSION_FIND_PSWD_QUESTION_ANSWERED);
		if (user == null || findPswdStat == null || findPswdStat != FindPswdStat.REQUEST_TO_ANSWER_QUESTION || tryAnswerTime == null
				|| tryAnswerTime >= 2) {
			// 步骤出错了
			// mav.set
		} else {
			tryAnswerTime++;
			WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_QUESTION_ANSWERED, tryAnswerTime);
			String securityQuestion = user.getSecurityQuestion();
			mav.addObject("securityQuestion", securityQuestion);
			if (user.getSecurityAnswer().equals(securityAnswer)) {
				WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_STAT, FindPswdStat.ANSWERED_QUESTION);
				mav.setViewName(ViewPaths.USER_RESETPASSWORD);
			} else {
				mav.setViewName(ViewPaths.USER_FINDPSWDBYANSWER);
			}
		}
		return mav;
	}

	/**
	 * 找回密码，检查token string
	 * 
	 * @param tokenStr
	 *            token string
	 * @return
	 */
	@RequestMapping(value = "/password/check/{tokenStr}", method = RequestMethod.GET)
	public ModelAndView checkFindPswdToken(@PathVariable String tokenStr) {
		ModelAndView mav = new ModelAndView();
		EmailToken token = emailTokenService.checkToken(tokenStr);
		if (token != null) {
			WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_STAT, FindPswdStat.CHECKED_TOKEN);
			User user = accountInfoService.getAccountInfoByUserID(token.getUserId());
			WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_USER, user);
			WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_CHECKED_TOKEN_ID, token.getId());
			mav.setViewName(ViewPaths.USER_RESETPASSWORD);
		} else {
			// 验证出错
			mav.addObject("errorMessage","验证出错<br>可能由以下几个原因:<br>1.验证码输入出错;<br>2.验证码已经过期(24小时);<br>请重试,谢谢!<br>");
			mav.setViewName(ViewPaths.USER_FINDPSWDREQUEST);
		}
		return mav;
	}

	/**
	 * 重置密码
	 * 
	 * @param newPassword
	 *            新密码
	 * @param newPasswordConfirm
	 *            确认新密码
	 * @return
	 */
	@RequestMapping(value = "/password/reset", method = RequestMethod.POST)
	public ModelAndView resetPassword(String newPassword, String newPasswordConfirm) {
		ModelAndView mav = new ModelAndView();
		User userInSession = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_FIND_PSWD_USER);
		FindPswdStat findPswdStat = (FindPswdStat) WebHelper.getSessionAttribute(null, Constant.SESSION_FIND_PSWD_STAT);
		if (userInSession != null && findPswdStat != null
				&& (findPswdStat.equals(FindPswdStat.ANSWERED_QUESTION) || findPswdStat.equals(FindPswdStat.CHECKED_TOKEN))) {

			if (newPassword.equals(newPasswordConfirm)) {
				accountInfoService.restPassword(userInSession.getId(), newPassword);
				if (findPswdStat.equals(FindPswdStat.CHECKED_TOKEN)) {
					Long tokenId = (Long) WebHelper.getSessionAttribute(null, Constant.SESSION_FIND_PSWD_CHECKED_TOKEN_ID);
					emailTokenService.updateToken(tokenId);
				}
				WebHelper.setSessionAttribute(null, Constant.SESSION_FIND_PSWD_STAT, FindPswdStat.FINISHED);

				mav.setViewName(ViewPaths.USER_ACCOUNTINFOMIDIFICATION);
				mav.addObject("title", "重置密码成功");
				mav.addObject("message", "恭喜，您已经成功重置了密码。");
				// 密码修改成功
			} else {
				mav.setViewName(ViewPaths.USER_RESETPASSWORD);
				// 密码出错
			}
		} else {
			// 步骤出错
		}

		return mav;
	}

	@RequestMapping(value = "/password/modify", method = RequestMethod.GET)
	public ModelAndView modifyPasswordRequest() {
		ModelAndView mav = new ModelAndView();
		User userInSession = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		if (userInSession != null && userInSession.getId() != 0) {
			mav.setViewName(ViewPaths.USER_MODIFYPASSWORD);
		}
		return mav;
	}

	/**
	 * 修改密码
	 * 
	 * @param password
	 *            原密码
	 * @param newPassword
	 *            新密码
	 * @param newPasswordConfirm
	 *            确认新密码
	 * @return
	 */
	@RequestMapping(value = "/password/modify", method = RequestMethod.POST)
	public ModelAndView modifyPasswordExecute(String password, String newPassword, String newPasswordConfirm) {
		ModelAndView mav = new ModelAndView();
		User userInSession = (User) WebHelper.getSessionAttribute(null, Constant.SESSION_USER);
		Long triedTime = (Long) WebHelper.getSessionAttribute(null, Constant.SESSION_MIDIFY_PSWD_TRY_TIME);
		if (triedTime == null) {
			triedTime = (long) 0;
		}
		if (userInSession != null && userInSession.getId() != 0 && triedTime < 2) {
			if (newPassword.equals(newPasswordConfirm)) {
				mav.addObject("errorMessage", "您两次所输入的密码不一致，请重试！");
			} else {
				boolean modifyResult = accountInfoService.modifyPassword(userInSession.getEmail(), password, newPassword);
				if (modifyResult == false) {
					WebHelper.setSessionAttribute(null, Constant.SESSION_MIDIFY_PSWD_TRY_TIME, triedTime + 1);
					mav.addObject("errorMessage", "您所输入的密码不正确，请重试！");
					mav.setViewName(ViewPaths.USER_MODIFYPASSWORD);
				} else {
					mav.setViewName(ViewPaths.USER_MODIFYPASSWORDSUCCESS);
				}
			}
			// 密码修改成功
		} else {
			// 密码出错
		}

		return mav;
	}

	/**
	 * 找回密码的状态
	 * 
	 * @author Jairus Chan
	 * 
	 */
	private enum FindPswdStat {
		REQUESTED, REQUEST_TO_ANSWER_QUESTION, ANSWERED_QUESTION, CHECKED_TOKEN, FINISHED,
	}

}
